﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataContexts.Supplier;

public partial class Supplier_Vehicle_Default : System.Web.UI.Page
{
    private SupplierDataContext supplierContext = new SupplierDataContext();

    private int SupplierId
    {
        get { return Helper.QSIntValue("sid"); }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ((BaseMasterPage)this.Master).CurrentPage = PageConfig.Pages.SupplierVehicle;
        if (!((BaseMasterPage)this.Master).AuthorizeCurrentUser())
            return;

        if (!IsPostBack)
        {
            LoadSuppliers();
            LoadSupplierVehicles();
            ddlSuppliers.Visible = UserAccess.IsCurrentUser(Enums.UserTypes.Admin);
        }
    }

    private void LoadSupplierVehicles()
    {
        gvSupplierVehicles.DataSource = from s in supplierContext.SupplierVehicles
                                        where s.SupplierId == Convert.ToInt32(ddlSuppliers.SelectedValue)
                                        select s;
        gvSupplierVehicles.DataBind();
        hpyAddNew.NavigateUrl = "addedit.aspx?sid=" + ddlSuppliers.SelectedValue;
    }

    private void LoadSuppliers()
    {
        ddlSuppliers.DataSource = supplierContext.Suppliers;
        ddlSuppliers.DataTextField = "SupplierName";
        ddlSuppliers.DataValueField = "SupplierId";
        ddlSuppliers.DataBind();

        if (UserAccess.IsCurrentUser(Enums.UserTypes.Supplier))
        {
            ddlSuppliers.SelectedValue = UserAccess.CurrentSupplier.SupplierId.ToString();
        }
        else
        {
            ddlSuppliers.SelectedValue = SupplierId.ToString();
        }
        
    }
    protected void gvSupplierVehicles_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Helper.ApplyDeleteConfirmMsg(e, 10);
        }
    }
    protected void gvSupplierVehicles_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {

    }
    protected void gvSupplierVehicles_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = Convert.ToInt32(gvSupplierVehicles.DataKeys[e.RowIndex].Value);
        var obj = supplierContext.SupplierVehicles.SingleOrDefault(u => u.SupplierVehicleId == id);

        supplierContext.SupplierVehicles.DeleteOnSubmit(obj);

        supplierContext.SubmitChanges();

        Response.Redirect("default.aspx");
    }

    protected void ddlSuppliers_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadSupplierVehicles();
    }
}
